package com.bbx.demo.socket.server;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import lombok.extern.slf4j.Slf4j;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.net.ServerSocket;
import java.net.Socket;


@Slf4j
public class SocketServer {

    public static void main (String [] args){
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            serverSocket = new ServerSocket(8888);
            socket = serverSocket.accept();
            socket.setSoTimeout(1000*60);
            inputStream = socket.getInputStream();

            log.info("start write file");
            try {
                FileUtil.writeFromStream(inputStream,
                        "C:\\Users\\kaifacs\\Downloads\\SCBH201105_20201111_Server.zip");
                log.info("end write file");
            } catch (IORuntimeException e) {
                log.error("write File timeout[{}]",e.getMessage());
            }


        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            //此处多个资源要分别进行try catch  避免其中一个出问题有其他的 也不能关闭

            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
